package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateOrderRequest;
import com.mall.order.dto.CreateOrderResponse;
import com.mall.order.dto.MyOrderDetailResponse;
import com.mall.order.dto.OrderDetailRequest;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author
 * @date 2020/12/20 16:08
 */
@Slf4j
@RestController
@RequestMapping("/shopping")
public class MyOrderController {
    //创建订单
    @Reference(timeout = 2000,retries = 0,check = false)
    OrderCoreService orderCoreService;

    //查询订单
    @Reference(timeout = 2000,retries = 0,check = false)
    OrderQueryService orderQueryService;

    @PostMapping("order")
    public ResponseData createOrder(@RequestBody CreateOrderRequest createOrderRequest, HttpServletRequest request){
        //在request中获取到user信息
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("id").toString());
        //将userId和uniqueKey一起塞进请求参数bean中
        createOrderRequest.setUserId(uid);
        createOrderRequest.setUniqueKey(UUID.randomUUID().toString());
        //创建订单
        CreateOrderResponse response = orderCoreService.createOrder(createOrderRequest);
        if (!response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil().setData(response.getOrderId());
    }

    @GetMapping("order/{id}")
    public ResponseData queryOrder(@PathVariable("id") String id){
        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
        orderDetailRequest.setOrderId(id);
        MyOrderDetailResponse response = orderQueryService.queryOrderDetail(orderDetailRequest);
        if (!response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil().setData(response.getMyOrderDetailInfo());
    }



}
